from django.db import transaction
from django.shortcuts import render, HttpResponse, redirect
from django import forms
from io import BytesIO

from app01.models import RegisterForm
from app01.utils.code import check_code
from app01 import models
from app01.utils.bootstrap import BootStrapForm
from app01.utils.encrypt import md5
import uuid
from django.contrib.auth import get_user_model
from django.urls import reverse_lazy
from django.views import generic

def generate_unique_org_id():
    return str(uuid.uuid4())

class LoginForm(BootStrapForm):
    username = forms.CharField(
        label="用户名",
        widget=forms.TextInput,
        required=True
    )
    password = forms.CharField(
        label="密码",
        widget=forms.PasswordInput(render_value=True),
        required=True
    )

    code = forms.CharField(
        label="验证码",
        widget=forms.TextInput,
        required=True
    )

    def clean_password(self):
        pwd = self.cleaned_data.get("password")
        return md5(pwd)

    def __init__(self, *args, request=None, **kwargs):
        self.request = request
        super().__init__(*args, **kwargs)


def login(request):
    """ 登录 """
    if request.method == "GET":
        form = LoginForm(request=request)
        return render(request, 'login.html', {'form': form})

    form = LoginForm(data=request.POST)
    if form.is_valid():
        # 验证成功，获取到的用户名和密码
        # {'username': 'wupeiqi', 'password': '123',"code":123}
        # {'username': 'wupeiqi', 'password': '5e5c3bad7eb35cba3638e145c830c35f',"code":xxx}

        # 验证码的校验
        user_input_code = form.cleaned_data.pop('code')
        code = request.session.get('image_code', "")
        if code.upper() != user_input_code.upper():
            form.add_error("code", "验证码错误")
            return render(request, 'login.html', {'form': form})

        # 去数据库校验用户名和密码是否正确，获取用户对象、None
        # admin_object = models.Admin.objects.filter(username=xxx, password=xxx).first()
        admin_object = models.Admin.objects.filter(**form.cleaned_data).first()
        if not admin_object:
            form.add_error("password", "用户名或密码错误")
            # form.add_error("username", "用户名或密码错误")
            return render(request, 'login.html', {'form': form})

        # 用户名和密码正确
        # 网站生成随机字符串; 写到用户浏览器的cookie中；再写入到session中；
        request.session["info"] = {'id': admin_object.id, 'name': admin_object.username}
        request.session['is_login'] = True
        request.session['admin_info'] = {'org_id': admin_object.org_id}
        # 指的是在服务器中保存session的信息为：{'id': admin_object.id, 'name': admin_object.username}这个字典
        # 这一句完成了cookie与session的全部过程
        # session可以保存7天
        request.session.set_expiry(60 * 60 * 24 * 7)

        return redirect("/admin/list/")


    return render(request, 'login.html', {'form': form})

def image_code(request):
    """ 生成图片验证码 """

    # 调用pillow函数，生成图片
    img, code_string = check_code()

    # 写入到自己的session中（以便于后续获取验证码再进行校验）
    request.session['image_code'] = code_string
    # 给Session设置60s超时
    request.session.set_expiry(60)

    stream = BytesIO()
    img.save(stream, 'png')
    return HttpResponse(stream.getvalue())

def logout(request):
    """ 注销 """

    request.session.clear()

    return redirect('/login/')


def register(request):
    # if request.session.get('is_login', None):
    #     return redirect("/admin/list/")

    if request.method == 'POST':
        register_form = RegisterForm(request.POST)
        if register_form.is_valid():   # 当输入的数据格式都合法的时候
            username = register_form.cleaned_data.get('username')
            password = register_form.cleaned_data.get('password')
            # password2 = register_form.cleaned_data.get('password2')
            # email = register_form.cleaned_data.get('email')
            # sex = register_form.cleaned_data.get('sex')
            # print(username, password1, password2, email, sex)

            # if password1 != password2:
            #     message = "两次输入的密码不一致"
            #     return render(request, 'register.html', locals())

            same_name_user = models.Admin.objects.filter(username=username)
            if same_name_user:
                message = "用户名已存在"
                register_form.add_error('username', message)
                return render(request, 'register.html',{'register_form': register_form})

            # same_email_user = models.Admin.objects.filter(email=email)
            # if same_email_user:
            #     message = "邮箱已经注册"
            #     return render(request, 'register.html', locals())
            # 生成唯一的org_id，这里可以使用一些随机生成算法或者结合时间戳等信息来生成

            username = register_form.cleaned_data.get('username')
            password = register_form.cleaned_data.get('password')
            org_id = username + "_" + generate_unique_org_id()
            new_user = models.Admin()
            new_user.username = username
            new_user.password = md5(password)
            new_user.org_id = org_id
            # new_user.email = email
            # new_user.sex = sex
            new_user.save()


            return redirect('/login/')
        else:  # 当输入的数据存在不合法的时候。
            # 比如输入ddd@ddd这个作为邮箱，此时前端的控件不会报错，
            # 后台在验证的时候会发现这个数据不符合，因此会运行这里的代码
            return render(request, 'register.html',{'register_form': register_form})

    register_form = RegisterForm()
    return render(request, 'register.html', {'register_form': register_form})
